package io.kiki.sba.registry.common.model.metaserver;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


public class Lease<T> implements Serializable {

    public static final String LEASE_DURATION = "registry.lease.duration.secs";
    public static final int DEFAULT_DURATION_SECS = Integer.getInteger(LEASE_DURATION, 20);

    @Setter
    @Getter
    private T renewal;

    @Getter
    private long beginTimestamp;

    @Getter
    private volatile long lastUpdateTimestamp;

    private long duration;

    public Lease(T renewal, long durationSECS) {
        this.renewal = renewal;
        this.beginTimestamp = System.currentTimeMillis();
        this.lastUpdateTimestamp = beginTimestamp;
        this.duration = durationSECS * 1000;
    }


    public Lease(T renewal, long duration, TimeUnit unit) {
        this(renewal, unit.toSeconds(duration));
    }

    public boolean isExpired() {
        return System.currentTimeMillis() > lastUpdateTimestamp + duration;
    }

    public void renew() {
        lastUpdateTimestamp = System.currentTimeMillis();
    }


    public void renew(long durationSECS) {
        lastUpdateTimestamp = System.currentTimeMillis();
        duration = durationSECS * 1000;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        Lease<?> lease = (Lease<?>) o;
        return beginTimestamp == lease.beginTimestamp && renewal.equals(lease.renewal);
    }

    @Override
    public int hashCode() {
        return Objects.hash(renewal, beginTimestamp);
    }
}
